package org.homly.admin.action.product;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.homly.admin.form.ProductForm;
import org.homly.service.ProductService;
import org.homly.sql.SQLTool;
import org.homly.tool.UploadFileTool;

public class SaveProductAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ProductForm paf = (ProductForm) form;
		// 修改
		if (paf != null && paf.getProductId() > 0) {
			updateProduct(request, paf);
			// 添加附加图片
			addProductExtPic(request, paf.getProductExtPic(), paf.getProductId());
			deleteProductExtPic(request);
		} else {// 新增
			FormFile formFile = paf.getProductPic();
			if (formFile != null && formFile.getFileSize() > 0) {
				paf.setProductPicUrl(UploadFileTool.uploadFile(request,
						formFile));
			}
			// 添加产品并且返回产品ID
			long productId = addProduct(paf);
			if (productId != 0) {
				// 添加附加图片
				addProductExtPic(request, paf.getProductExtPic(), productId);
			}
		}
		return new ActionForward(mapping.findForward("success").getPath()
				+ "?id=" + paf.getConfigId(), true);
	}

	/**
	 * 更新产品
	 * 
	 * @param paf
	 */
	private void updateProduct(HttpServletRequest request, ProductForm paf) {

		FormFile formFile = paf.getProductPic();
		if (formFile != null && formFile.getFileSize() > 0) {
			paf.setProductPicUrl(UploadFileTool.uploadFile(request, formFile));
		}
		String sql = "update product set product_no=?,product_brand_name=?,product_name=?,product_pic_url=?,product_price=?," +
				"product_stock=?,product_parameter=?,product_note=?,product_warranty_deadline=?,product_status=?," +
				"product_modify_time=? where product_id=?";
		Object[] para = {paf.getProductNo(), paf.getProductBrandName(),
				paf.getProductName(), paf.getProductPicUrl(),
				paf.getProductPrice(), paf.getProductStock(),
				paf.getProductParameter(), paf.getProductNote(),
				paf.getProductWarrantyDeadline(), paf.getProductStatus(),
				new Date(), paf.getProductId()};
		try {
			SQLTool.update(sql, para);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新增产品
	 * 
	 * @param paf
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private long addProduct(ProductForm paf) {

		String sql = "insert into product(config_id,product_no,product_brand_name," +
				"product_name,product_pic_url,product_price,product_stock," +
				"product_parameter,product_note,product_warranty_deadline," +
				"product_sort_no,product_status,product_create_time) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
		Object[] para = {paf.getConfigId(), paf.getProductNo(), paf.getProductBrandName(),
				paf.getProductName(), paf.getProductPicUrl(), paf.getProductPrice(), paf.getProductStock(),
				paf.getProductParameter(), paf.getProductNote(), paf.getProductWarrantyDeadline(),
				ProductService.getProductBottomSortNo(), paf.getProductStatus(), new Date()};
		try {
			SQLTool.insert(sql, para);
			sql = "select max(product_id) productId from product";
			List list = SQLTool.query(sql);
			if (list != null && list.size() > 0) {
				String productIdStr = ((HashMap<String, String>) list.get(0))
						.get("productId");
				return Long.parseLong(productIdStr);
			} else {
				return 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 添加产品的附加图片
	 * 
	 * @param formFileList
	 */
	private void addProductExtPic(HttpServletRequest request,
			List<FormFile> formFileList, long productId) {
		if (formFileList != null) {
			for (FormFile formFile : formFileList) {
				if (formFile != null && formFile.getFileSize() > 0) {
					String url = UploadFileTool
							.uploadFile(request, formFile, 1);
					String sql = "insert into product_append_pic(product_id,product_append_pic_url,product_append_pic_name,product_append_pic_status,product_append_pic_create_time)"
							+ " values(?,?,?,?,?)";
					Object[] para = { productId, url, UploadFileTool.getFileBasicName(formFile.getFileName()),
							1, new Date() };
					try {
						SQLTool.insert(sql, para);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 删除附加图片
	 * 
	 * @param request
	 */
	private void deleteProductExtPic(HttpServletRequest request) {

		String dapIdsS = request.getParameter("deleteAppendPicIds");
		if (dapIdsS == null) {
			return ;
		}
		String[] dapIdsSArray = dapIdsS.split(",");
		int dapIdsSArrayLength = dapIdsSArray.length;
		if (dapIdsSArray == null || dapIdsSArrayLength <= 1) {
			return ;
		}
		ServletContext servletContext = request.getSession().getServletContext();
		for (int i = 1; i < dapIdsSArrayLength; i ++) {
			try {
				Integer dapId = Integer.valueOf(dapIdsSArray[i]);
				String dapUrl = ProductService.getProductAppendPicUrlById(dapId);
				File dap = new File(servletContext.getRealPath(dapUrl));
				dap.delete();
				ProductService.deleteProductAppendPicById(dapId);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
